package com.ningju.procurement.common.mybatis.pager;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PageSpingMvcInterceptor extends HandlerInterceptorAdapter {
	
	//Logger LOG = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		PageParam pageParam = PageContext.getPage();
		
		if(null == pageParam) {
			pageParam = new PageParam();
		}
		pageParam.setPage(PageParam.C_DEFAULT_CURPAGE);
		pageParam.setPageSize(PageParam.C_DEFAULT_PAGESIZE);
		
		if(StringUtils.isNotEmpty(page)) {
			pageParam.setCount(null);
			
			try {
				pageParam.setPage(Integer.valueOf(page));
			} catch(NumberFormatException e) {
				pageParam.setPage(PageParam.C_DEFAULT_CURPAGE);
			}

			try {
				if(StringUtils.isNotEmpty(pageSize)) {
					pageParam.setPageSize(Integer.valueOf(pageSize));
				}
			} catch(NumberFormatException e) {
				pageParam.setPageSize(PageParam.C_DEFAULT_PAGESIZE);
			}
		}
		PageContext.setPage(pageParam);
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		if(modelAndView != null) {
			modelAndView.addObject("pageParam", PageContext.getPage());
		}
	}

}